<?php
/**
 * AttachmentService.class.php 
 * Created Time 2016年3月24日 上午9:41:44
 *
 * @author     Xiaodc
 * @copyright  Copyright (c) 2005-2015 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

namespace Component\Service;
use Component\Common\BaseService;

class AttachmentService extends BaseService
{
    /**
     * 读取文件
     * 
     * @param int $atid
     * @param array $options
     * 
     * @return bool
     * */
    public function read($atid, $options)
    {
        // 查看附件是否存在
        $attModel = D ('Attachment');
        $aid = intval($atid);
        $attInfo = $attModel->where('atid=%d', $aid)->find();
        if(!$attInfo)
        {
            throw new \Exception(L('_ERR_ATT_NOT_EXITS_', array('id'=>$aid)));
        }
        
        // 显示文件了
        
        // 获取文件路径
        $uploadDir = rtrim(C('upload.rootPath'), '/') .'/';
        $savePath = trim($attInfo['atpath'], '/') .'/';
        $saveName = $attInfo['atname'];
        $filePath = $uploadDir.$savePath.$saveName;
        $relPath = realpath($filePath);
        // 验证文件是否存在
        if(!file_exists($relPath))
        {
            throw new \Exception(L('_ERR_ATT_FILE_NOT_EXITS_'));
        }
        // 最后修改时间
        $filemtime = filemtime($relPath);
        
        $resp = \Component\Common\Response::get_instance();
        $resp->set_raw_header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $filemtime) . ' GMT');
        
        // 尝试发送 304响应强制浏览器使用缓存
        if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && ($HTTP_IF_MODIFIED_SINCE = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $filemtime)) {
            $resp->set_raw_header('Etag: ');
            $resp->set_raw_header("HTTP/1.1 304 Not Modified");
            $resp->send_headers();
            return true;
        }
        
        // 附件文件的 mime 类型字符串
        $mime = $attInfo['atmine'];
        // 清除输出缓冲
        @ob_end_clean();
        
        // 处理名称里的符号，避免chrome无法解析问题
        $attInfo['atname'] = str_replace(array(
                '&',
                '=',
                ','
        ), '_', $attInfo['atname']);
        
        if (!$options['download']) {
            $resp->set_raw_header('Content-Disposition: inline; filename=' . $attInfo['atname']);
            $resp->set_raw_header('Content-Type: ' . $mime);
        } else {
            $resp->set_raw_header('Content-Disposition: attachment; filename=' . $attInfo['atname']);
            $resp->set_raw_header('Content-Type: ' . $mime);
        }
        
        
        if (!is_file($relPath)) {
            return true;
        }
        
        // 发送浏览器头
        $resp->set_raw_header("Content-Length: " . filesize($relPath));
        $resp->send_headers();
        
        $fp = fopen($filePath, 'rb');
        if ($fp) {
            fseek($fp, 0);
            if (function_exists('fpassthru')) {
                fpassthru($fp);
            } else {
                echo @fread($fp, filesize($relPath));
            }
        }
        
        fclose($fp);
        
        flush();
        ob_flush();
        return true;
        
    }
}
